﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CPPEI.WebApi
{
    public static class ActionEntry
    {
        static JsonSerializerSettings s_settings;

        static ActionEntry()
        {
            // 初始化代码在这里开发
            // 加载 配置
            Intergration.Config.Init();


            CPPEI.WebApi.ActionFactory.InitByConfig();


            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            s_settings = new JsonSerializerSettings();
            s_settings.Converters.Add(timeFormat);
        }

        public static void ProcessRequest(HttpContext context)
        {
            SysParameters sysParameters = GetParameter(context.Request);
            IAction action = ActionFactory.GetAction(sysParameters);
            if (action != null)
            {
                ActionResult result = action.Execute(context.Request, sysParameters);
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result, Formatting.Indented, s_settings));
            }
            else
            {
                ActionResult result = new ActionResult(false, ErrorCode.ActionNotFound, ErrorCode.ToString(ErrorCode.ActionNotFound), null);

                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result, Formatting.Indented, s_settings));
            }
        }

        private static SysParameters GetParameter(HttpRequest request)
        {
            SysParameters parameters = new SysParameters();
            if(request.HttpMethod == HttpMethods.POST)
            {
                parameters.Scenario = request.Form["sys:sno"];
                parameters.Action = request.Form["sys:act"];
                parameters.Version = request.Form["sys:ver"];
                parameters.Token = request.Form["sys:token"];
            }
            else if(request.HttpMethod == HttpMethods.GET)
            {
                parameters.Scenario = request.QueryString["sys:sno"];
                parameters.Action = request.QueryString["sys:act"];
                parameters.Version = request.QueryString["sys:ver"];
                parameters.Token = request.QueryString["sys:token"];
            }

            return parameters;
        }
    }
}
